
public class ArrayList {
    public int[] elem;
    public int useSize;

    public ArrayList() {
        this.elem = new int[10];
    }

    /**
     * 在pos位置新增元素
     */
    public void add(int pos, int data) {
        //1. 判断 elem数组满了没有
        if (this.elem.length == this.useSize) {
            System.out.println("数组已满!");
            return;
        }
        //2. 判断pos位置的合法性
        if (pos < 0 || pos > useSize) {
            System.out.println("pos位置不合法");
            return;
        }
        //3. 如果pos位置==useSize
/*        if (pos == this.useSize) {
            this.elem[pos] = data;
            this.useSize++;
            return;
        }*/
        //4. 数组元素往后移
        for (int i = useSize - 1; i >= pos; i--) {
            this.elem[i + 1] = this.elem[i];
        }
        this.elem[pos] = data;
        this.useSize++;
    }

    /**
     * 打印顺序表
     */
    public void display() {
        for (int i = 0; i < this.useSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }

    /**
     * 判断是否包含toFind这个元素
     */
    public boolean contains(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if (this.elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    /**
     * 查找某个元素对应的位置
     */
    public int search(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if (this.elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 获取 pos位置的元素
     */
    public int getPos(int pos) {
        //顺序表为空
        if (isEmpty()) {
            return -1;
        }
        // pos位置不合法
        if (pos < 0 || pos >= this.useSize) {
            return -1;
        }
        return this.elem[pos];
    }

    public boolean isEmpty() {
        return this.useSize == 0;
    }

    /**
     * 给 pos位置的元素设为 value
     */
    public void updataPos(int pos, int value) {
        //顺序表为空
        if (isEmpty()) {
            return;
        }
        // pos位置不合法
        if (pos < 0 || pos >= this.useSize) {
            return;
        }
        this.elem[pos] = value;
    }

    /**
     * 删除第一次出现的关键字key
     */
    public void remove(int key) {
        int index = this.search(key);
        if (key == -1) {
            System.out.println("删除的" + key + "不存在");
        }
        int i = index;
        for (; i < this.useSize - 1; i++) {
            this.elem[i] = this.elem[i + 1];
        }
        this.useSize--;
    }

    /**
     * 获取顺序表长度
     * @return
     */
    public int size() {
        return this.useSize;
    }

    /**
     * 清空顺序表
     */
    public void clear() {
        this.useSize = 0;
        //this.elem = null;
    }
}


